#include "qinglongtrobot.h"
#include <QJsonArray>
#include <udpcommunicate.h>
#include<QThread>
#include <QTimer>


QingLongRobot::QingLongRobot(QObject *parent)
    : QObject{parent}
{

    this->_iniJoints();//初始化结构体，各个关节的信息
}
/**
     * @introduce   初始化关节的信息
     * @author      毛辰飞
     * @data        2024/11/15
**/
void QingLongRobot::_iniJoints()
{
    /* 创建udp接收线程 */
    QThread *pUdpThread= new QThread;
    UDPCommunicate *pUdpCommunicate = new UDPCommunicate("127.0.0.1","127.0.0.1",39292,39392);
    pUdpCommunicate->moveToThread(pUdpThread);
    connect(pUdpThread, SIGNAL(started()),  pUdpCommunicate, SLOT(slot_init()));
    connect(pUdpThread, SIGNAL(finished()), pUdpCommunicate, SLOT(deleteLater()));
    connect(pUdpThread, SIGNAL(finished()), pUdpCommunicate, SLOT(slot_stop()));
    connect(this,SIGNAL(signal_udpData(QByteArray)),pUdpCommunicate,SLOT(slot_send(QByteArray)));//测试
    pUdpThread->start();
    QTimer *pTimer=new QTimer;
    connect(pTimer,&QTimer::timeout,[=]{
        emit signal_udpData(this->toJson().toJson());
    });
    pTimer->start(1000);

}
/**
     * @introduce   map转序列化为json格式
     * @author      毛辰飞
     * @data        2024/11/14
**/

QJsonDocument QingLongRobot::toJson() const
{
    // qDebug()<<"QingLongRobot tojson"<<QThread::currentThreadId();
    //关节的全部映射
    QMap<QString, QVariant> mapJoint = QMap<QString, QVariant>();
    //json头映射
    QMap<QString, QVariant> headMap; // 假设您已经有一个QMap<QString, int>对象
    headMap.insert("data_type","request_control");
    headMap.insert("value",true);
    mapJoint.insert("data_info",headMap);
    //json头映射
    QMap<QString, QVariant> robotinfoMap; // 假设您已经有一个QMap<QString, int>对象
    robotinfoMap.insert("robot_state","state1");
    robotinfoMap.insert("head_state","state1");
    robotinfoMap.insert("waist_state","state1");
    robotinfoMap.insert("arm_state","state1");
    robotinfoMap.insert("leg_state","state1");
    robotinfoMap.insert("battery_state","running");
    robotinfoMap.insert("imu_state","running");
    robotinfoMap.insert("battery_soe",100);
    mapJoint.insert("robot_info",robotinfoMap);

    //获取更新的关节数据 key为关节名称 value为关节信息
    for(QHash<QString,JointBase*>::iterator i=ReadJoints::getInstance().GetJointBaseParamsValue().begin();
         i!=ReadJoints::getInstance().GetJointBaseParamsValue().end();i++){
        mapJoint.insert(i.key(),i.value()->GetData());
    }


    //map->json
    QJsonDocument doc = QJsonDocument::fromVariant(QVariant(mapJoint));

    QString jsonString = doc.toJson(QJsonDocument::Compact);

    return doc;

}
void QingLongRobot::fromJson(const QJsonDocument &jsonObj)
{

}
